package com.gw.vip.center.auth;

import com.gw.vip.center.constant.VipCenterKey;
import com.gw.vip.center.jwt.JwtUtil;
import com.gw.vip.center.jwt.TokenInfo;
import com.gw.vip.common.exception.ExceptionEnums;
import com.gw.vip.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: GW
 * @since: 2022/4/14
 * @description:
 **/
@Slf4j
@Aspect
@Component
public class CheckTokenAspect {
    /**
     * 以自定义 @CheckToken 注解作为切面入口
     */
    @Pointcut("@annotation(com.gw.vip.center.auth.CheckToken)")
    public void checkToken() {
    }

    @Around("checkToken()")
    public Object checkToken(ProceedingJoinPoint point) throws Throwable {
        //从head里获取token
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
        if (attributes==null){
            log.error("参数不存在！");
            throw new ServiceException(ExceptionEnums.ERROR_PARAMS);
        }
        HttpServletRequest  request = attributes.getRequest();

        String token = request.getHeader("X-Token");
        if (token==null){
            log.error("token不存在！");
            throw new ServiceException(ExceptionEnums.ERROR_PARAMS, "token未上送！");
        }

        TokenInfo tokenInfo;
        try{
            if (!JwtUtil.verify(token)){
                log.error("token校验失败！");
                throw new ServiceException(ExceptionEnums.INVALID_TOKEN);
            }
            tokenInfo = JwtUtil.parse(token);
        }catch (Exception e){
            log.error("", e);
            throw new ServiceException(ExceptionEnums.INVALID_TOKEN, "无效token");
        }

        request.setAttribute(VipCenterKey.TOKEN_INFO, tokenInfo);
        return point.proceed();
    }
}
